package com.jjb.saas.cert.infrastructure.utils;


import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import static javax.print.attribute.ResolutionSyntax.DPI;

@Slf4j
public class PdfUtil {
    public PdfUtil() {
    }


    /**
     * 生成临时文件
     * @param fileExtension
     * @return
     */
    private static String getTempPath(String fileExtension) {
        StringBuffer sb = new StringBuffer()
                .append(System.getProperty("java.io.tmpdir"))
                .append("/")
                .append(System.currentTimeMillis())
                .append("_")
                .append(UUID.randomUUID().toString().replaceAll("-", ""))
                .append(".")
                .append(fileExtension);
        return sb.toString();
    }

    /**
     * PDF转图片
     * @param pdfPath：PDF文件
     * @return : 图片文件
     */
    public static List<String> pdfToImage(String pdfPath) {
        List<String> filePath = new LinkedList<>();
        PDDocument document = null;
        BufferedImage bufferedImage = null;
        try {
            document =  PDDocument.load(new File(pdfPath));
            PDFRenderer pdfRenderer = new PDFRenderer(document);

            for ( int page = 0;  page < document.getNumberOfPages(); ++ page ) {
                bufferedImage = pdfRenderer.renderImageWithDPI(page, DPI);
                String file = getTempPath("jpg");
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(file);
                    ImageIO.write(bufferedImage, "jpg", fileOutputStream);
                    filePath.add(file);
                }finally {
                    if ( fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                }

            }

            return filePath;
        }catch (Exception e) {
            throw new RuntimeException("PDF转图片失败:"+e.getMessage(), e);
        }finally {
            try {document.close();} catch (Exception e) {}
        }
    }

    public static void imageToPdf(String imgPath, String targetPath) throws IOException {
        Document document = null;
        FileOutputStream fos = null;

        try {
            document = new Document();
            document.setMargins(0.0F, 0.0F, 0.0F, 0.0F);
            fos = new FileOutputStream(targetPath);
            PdfWriter.getInstance(document, fos);
            document.open();
            Image image = Image.getInstance(imgPath);
            float imageHeight = image.getScaledHeight();
            float imageWidth = image.getScaledWidth();
            Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
            document.setPageSize(rectangle);
            image.setAlignment(1);
            document.newPage();
            document.add(image);
            fos.flush();
        } catch (DocumentException var11) {
            throw new RuntimeException(var11);
        } finally {
            if (document != null) {
                document.close();
            }

            if (fos != null) {
                fos.close();
            }

        }

    }

    public static void imageToPdf(List<String> imgPathList, String targetPath) throws IOException {
        Document document = null;
        FileOutputStream fos = null;

        try {
            document = new Document();
            document.setMargins(0.0F, 0.0F, 0.0F, 0.0F);
            fos = new FileOutputStream(targetPath);
            PdfWriter.getInstance(document, fos);
            document.open();
            Iterator var4 = imgPathList.iterator();

            while(var4.hasNext()) {
                String s = (String)var4.next();
                Image image = Image.getInstance(s);
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();
                Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
                document.setPageSize(rectangle);
                image.setAlignment(1);
                document.newPage();
                document.add(image);
            }

            fos.flush();
        } catch (DocumentException var13) {
            throw new RuntimeException(var13);
        } finally {
            if (document != null) {
                document.close();
            }

            if (fos != null) {
                fos.close();
            }

        }
    }

    public static void mergImage(List<String> imgs, String outPath) {

        File file = new File(outPath);
        File pfile = file.getParentFile();
        if (! pfile.exists() ) {
            pfile.mkdirs();
        }

        try {
            InputStream imagein = new FileInputStream((String)imgs.get(0));
            BufferedImage image = ImageIO.read(imagein);
            BufferedImage bg_image = new BufferedImage(image.getWidth(), image.getHeight() * imgs.size(), 4);
            Graphics g = bg_image.getGraphics();
            g.drawImage(image, 0, 0, (ImageObserver)null);
            imagein.close();

            for(int i = 1; i < imgs.size(); ++i) {
                imagein = new FileInputStream((String)imgs.get(i));
                image = ImageIO.read(imagein);
                g.drawImage(image, 0, image.getHeight() * i, (ImageObserver)null);
                imagein.close();
            }

            OutputStream outImage = new FileOutputStream(outPath);
            ImageIO.write(bg_image, "jpg", outImage);
            outImage.close();
        } catch (Exception var7) {
            log.info(var7.getStackTrace().toString());
        }

    }



}

